package com.tonghe.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.fastjson.JSON;
import com.tonghe.domain.ResponseResult;
import com.tonghe.domain.entity.Category;
import com.tonghe.enums.AppHttpCodeEnum;
import com.tonghe.service.CategoryService;
import com.tonghe.utils.BeanCopyUtils;
import com.tonghe.utils.WebUtils;
import com.tonghe.vo.PageVo;
import com.tonghe.vo.sys.ExportCategoryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @Date:2022/9/8- 09- 08- 11:15
 **/
@RestController
@RequestMapping("/content/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /** 列出所有分类 */
    @GetMapping("/listAllCategory")
    public ResponseResult getAllCategory() {
        return categoryService.listAllCategory();
    }

    /** 到处所有分类 */
    @PreAuthorize("@ps.hasPermi('content:category:export')")
    @GetMapping("/export")
    public void export(HttpServletResponse response){
        try {
            WebUtils.setDownLoadHeader("分类.xlsx", response);
            List<Category> list = categoryService.list();
            List<ExportCategoryVo> exportCategoryVos = BeanCopyUtils.copyBeanList(list, ExportCategoryVo.class);
            EasyExcel.write(response.getOutputStream(),ExportCategoryVo.class).autoCloseStream(Boolean.FALSE).sheet("分类")
                    .doWrite(exportCategoryVos);
        } catch (IOException e) {
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR);
            WebUtils.renderString(response,JSON.toJSONString(result));
        }
    }
    @PutMapping
    public ResponseResult edit(@RequestBody Category category){
        categoryService.updateById(category);
        return ResponseResult.okResult();
    }

    @DeleteMapping(value = "/{id}")
    public ResponseResult remove(@PathVariable(value = "id")Long id){
        categoryService.removeById(id);
        return ResponseResult.okResult();
    }

    @GetMapping(value = "/{id}")
    public ResponseResult getInfo(@PathVariable(value = "id")Long id){
        Category category = categoryService.getById(id);
        return ResponseResult.okResult(category);
    }
    @PostMapping
    public ResponseResult add(@RequestBody Category category){
        categoryService.save(category);
        return ResponseResult.okResult();
    }
    /**
     * 获取用户列表
     */
    @GetMapping("/list")
    public ResponseResult list(Category category, Integer pageNum, Integer pageSize) {
        PageVo pageVo = categoryService.selectCategoryPage(category,pageNum,pageSize);
        return ResponseResult.okResult(pageVo);
    }

}
